<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

use Auth;

class SessionsController extends Controller
{

	 // 检测用户是否登录，无登录跳转到登录页面
    public function __construct()
    {
        $this->middleware('auth',[

            'except' => ['create','store']

        ]);
        $this->middleware('guest', [
            'only' => ['create']
        ]);
    }

    //登录表单
    public function create()
    {	

        return view('auth.login');
    }

    //验证身份
    public function store(Request $request)
    {
    	$credentials = $this->validate($request, [
           'name' => 'required|max:50',
           'password' => 'required'
       ]);

       if (Auth::attempt($credentials)) {
           // 登录成功后的相关操作
       		return redirect('user');

       } else {
           // 登录失败后的相关操作
       	return '请输入正确的账号';
       }

    }

    public function destroy()
    {
        Auth::logout();
        session()->flash('success', '您已成功退出！');
        return redirect('login');
    }

    //创建管理用户
    public function createadd(Request $request){

		// 用户信息写入数据库
          $user = User::insert([
            'name' => $request->name,
            'password' => bcrypt($request->password),
            'vip'=>2,
        ]);

         //添加成功
    	if($user){

    		return back();
    	}

    }

    //系统安全修改密码
    public function updpwd(Request $request){

      if($request->pwd == $request->forpwd){

        $status = User::where('name',$request->name)->update(['password'=>bcrypt($request->pwd)]);

        if($status){
          Auth::logout();
          return redirect('login');
        }
      }
    }

    public function uppwd(){

      return view('user.adminup');
    }
}
